import {Component, OnInit} from "@angular/core";
import {FormControl, FormGroup, FormBuilder, Validators} from "@angular/forms";
import {Hero} from "./hero";

@Component({
  selector: 'ng-form',
  templateUrl: './ng-form.component.html',
  styleUrls: ['./ng-form.component.scss']
})
export class NgFormComponent implements OnInit {
  private nameControl = new FormControl("Misty")

  private fbModel
  private fbModelSku

  private person = new FormGroup({
    firstName: new FormControl("Nate"),
    lastName: new FormControl("Murray"),
    age: new FormControl(25)
  })

  private heroPowers = ['Really Smart', 'Super Flexible', 'Super Hot', 'Weather Changer']
  private hero = new Hero(42, "SkyDog",
    this.heroPowers[1],
    'Leslie Rollover')

  constructor(_fb: FormBuilder) {
    this.fbModel = _fb.group({
      'sku': ['', Validators.compose([Validators.required, skuValidator])],
      'age': [10]
    })
    this.fbModelSku = this.fbModel.controls['sku']
  }

  ngOnInit() {
    this.fbModel.valueChanges.subscribe(v => {
      console.log("subscribe", v)
    })
  }

  onNgFormSubmit(value) {
    console.log("NgForm", value)
  }

  onFormBuilderSubmit(value) {
    console.log("FormBuilder", value)
  }

  onDocsFormSubmit(value) {
    console.log("DocsForm", value)
  }

  onChange() {
    console.log(this.nameControl)
  }
}

function skuValidator(control: FormControl): {[s: string]: boolean} {
  if (!control.value.match(/^123/)) {
    return {invalidSku: true}
  }
}